<template>
    <div class="editor-container">
      <Toolbar
        :editor="editorRef"
        :defaultConfig="toolbarConfig"
        :mode="mode"
        style="border-bottom: 1px solid #ccc"
      />
      <Editor
        :defaultConfig="editorConfig"
        :mode="mode"
        v-model="valueHtml"
        style="height: 800px; overflow-y: hidden"
        @onCreated="handleCreated"
        @onChange="handleChange"
      />
    </div>
  </template>
  
  <script lang="ts" setup>
  import '@wangeditor/editor/dist/css/style.css'
  import { onBeforeUnmount, ref, shallowRef } from 'vue'
  import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
  
  // 编辑器实例，必须用 shallowRef
  const editorRef = shallowRef()
  
  // 内容 HTML
  const valueHtml = ref('')
  
  // 编辑器配置
  const editorConfig = {
    placeholder: '请输入备注内容...',
    MENU_CONF: {
      uploadImage: {
        // 自定义上传图片
        async customUpload(file: File, insertFn: Function) {
          // file 即选中的文件
          // 自己实现上传，并得到图片 url
          // 最后插入图片
          // insertFn(url, alt, href)
        }
      }
    }
  }
  
  // 工具栏配置
  const toolbarConfig = {
    excludeKeys: [
      'group-video',
      'group-image',
      'insertTable',
      'codeBlock',
      'divider',
      'emotion',
      'group-more-style'
    ]
  }
  
  // 组件销毁时，也及时销毁编辑器
  onBeforeUnmount(() => {
    const editor = editorRef.value
    if (editor == null) return
    editor.destroy()
  })
  
  // 编辑器创建完成时的回调
  const handleCreated = (editor: any) => {
    editorRef.value = editor // 记录 editor 实例，重要！
  }
  
  // 编辑器内容、选区变化时的回调
  const handleChange = (editor: any) => {
    console.log('change:', editor.getHtml())
  }
  
  // 组件模式
  const mode = 'default' // 或 'simple'
  
  // 暴露方法给父组件
  defineExpose({
    getHtml: () => valueHtml.value,
    setHtml: (html: string) => {
      valueHtml.value = html
    }
  })
  </script>
  
  <style scoped>
  .editor-container {
    border: 1px solid #ccc;
    z-index: 100;
  }
  
  :deep(.w-e-text-container) {
    height: 900px !important;
  }
  </style>
